package com.hua.syn;
//不安全的取钱
//两个人使用相同的账户去银行取钱；

public class UnsafeBank {


    public static void main(String[] args) {
        //账户
        Account account = new Account(1000,"结婚基金");
        Drawing you = new Drawing(account, 50, "你");
        Drawing wifi = new Drawing(account, 100, "你媳妇");

        you.start();
        wifi.start();
    }











}

class Account{
    int money;//余额
    String name;//卡名

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}
//银行，模拟取款
class Drawing extends Thread{
    Account account;
    //
    int drawiongMoney;
    //现在
    int nowMoney;
    public Drawing(Account account,int drawiongMoney,String name){
        super(name);
        this.account = account;
        this.drawiongMoney = drawiongMoney;

    }
        //synchronized默认锁的对象是this
    @Override
    public  void run() {
        synchronized (account){ //锁的对象是变化的量，需要曾删改查的对象

            if (account.money-drawiongMoney<0){
                System.out.println(Thread.currentThread().getName()+"--->钱不够");
                return;
            }
            //模拟延时 ,可以放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            //卡内余额 = 余额 -  你取得钱
            account.money = account.money - drawiongMoney;
            //你手里得钱
            nowMoney = nowMoney + drawiongMoney;
            System.out.println(account.name+"的余额位："+account.money);
            //this.getName() == Thread.currentThread().getName()
            System.out.println(this.getName()+"手里得钱："+nowMoney);


        }


    }
}
